#include "findpasswordwidget.h"
#include "ui_findpasswordwidget.h"
#include <QMessageBox>

FindPasswordWidget::FindPasswordWidget(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::FindPasswordWidget)
{
    ui->setupUi(this);

    setWindowTitle("找回密码");

    connect(&userService, &UserService::sendMessageSuccess,
            [=](QString verifyCode)
    {
        ui->pushButtonGetVerifyCode->setEnabled(false);
        if(!myTimer->isActive())
        {
            myTimer->start(1000);
        }
        this->verifyCode = verifyCode;
    });
}

FindPasswordWidget::~FindPasswordWidget()
{
    delete ui;
}

void FindPasswordWidget::showAndInit(){
    this->verifyCode.clear();
    this->username.clear();
    ui->pushButtonGetVerifyCode->setEnabled(true);
    ui->pushButtonGetVerifyCode->setText("获取验证码");

    ui->lineEditUsername->clear();
    ui->lineEditPassword1->clear();
    ui->lineEditPassword2->clear();
    ui->lineEditVerifyCode->clear();

    myTimer = new QTimer();

    connect(myTimer, &QTimer::timeout,
            [=]()
    {
        static int i=60;
        i--;
        if(i==0){
            this->verifyCode = "";
            ui->pushButtonGetVerifyCode->setEnabled(true);
            ui->pushButtonGetVerifyCode->setText("获取验证码");
            if(myTimer->isActive())
            {
                i = 60;
                myTimer->stop();
            }
        }else{
            ui->pushButtonGetVerifyCode->setText(QString("重新获取(%1)").arg(i));
        }
    });

    exec();
}

void FindPasswordWidget::on_pushButtonGetVerifyCode_clicked()
{
    ui->pushButtonGetVerifyCode->setEnabled(false);
    this->username = ui->lineEditUsername->text();
    userService.sendMessage(this, this->username);
}

void FindPasswordWidget::on_pushButtonCancel_clicked()
{
    if(myTimer->isActive()){
        myTimer->stop();
        free(myTimer);
    }
    this->close();
}

void FindPasswordWidget::on_pushButtonSubmit_clicked()
{
    if(this->verifyCode != ui->lineEditVerifyCode->text()){
        QMessageBox::warning(this, "警告", "验证码错误！");
        return;
    }

    if(this->username != ui->lineEditUsername->text()){
        QMessageBox::warning(this, "警告", "输入用户名和获取验证码用户名不同！");
        return;
    }

    userService.findPassword(
                this,
                ui->lineEditUsername->text(),
                ui->lineEditPassword1->text(),
                ui->lineEditPassword2->text());
}
